package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/9/28.
 */
@WebServlet(name = "LastAccessTimeServlet",urlPatterns = "/lastAccessTimeServlet")
public class LastAccessTimeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        /**
         * 1.获得cookies
         */
        Cookie[] cookies=request.getCookies();
       String lastTime=null;
       for (int i=0;cookies !=null && i<cookies.length;i++){
           String name=cookies[i].getName();
           if("lastAccessTime".equals(name)){//key
               lastTime=cookies[i].getValue();//value
               break;
           }
       }

       //判断上次访问的时间是否空
        if(lastTime==null){
           out.write("您是第一次访问");
        }else{
            out.write("您上次访问的时间是"+lastTime);
        }
        //把当前的时间，要带给浏览器。key - value(String)
        //new Date();//1020530 2017-2-3 10:20:10  时间-->字符串
        String currenTime =new SimpleDateFormat("yyy-MM-dd#HH:mm:ss").format(new Date());
        Cookie cookie=new Cookie("lastAccessTime",currenTime);
        response.addCookie(cookie);
    }
}
